//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://www.nopCommerce.com/License.aspx. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.Common.Utils;

namespace NopSolutions.NopCommerce.Web.Administration.Modules
{
    public partial class ProductInfoControl : BaseNopAdministrationUserControl
    {
        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            if (!IsPostBack) {
                this.FillDropDowns();
                this.BindData();
            }
        }

        private void FillDropDowns() {
            this.ddlTemplate.Items.Clear();
            var productTemplateCollection = this.TemplateService.GetAllProductTemplates();
            foreach (ProductTemplate productTemplate in productTemplateCollection) {
                ListItem item2 = new ListItem(productTemplate.Name, productTemplate.ProductTemplateId.ToString());
                this.ddlTemplate.Items.Add(item2);
            }
        }

        private void BindData() {
            Product product = this.ProductService.GetProductById(this.ProductId);

            if (this.HasLocalizableContent) {
                var languages = this.GetLocalizableLanguagesSupported();
                rptrLanguageTabs.DataSource = languages;
                rptrLanguageTabs.DataBind();
                rptrLanguageDivs.DataSource = languages;
                rptrLanguageDivs.DataBind();
            }

            if (product != null) {
                this.txtName.Text = product.Name;
                this.txtShortDescription.Text = product.ShortDescription;
                this.txtFullDescription.Text = product.FullDescription;
                this.txtAdminComment.Text = product.AdminComment;

                CommonHelper.SelectListItem(ddlTemplate, product.TemplateId);
                CommonHelper.SelectListItem(ddlProductType, product.ProductTypeId);

                this.cbShowOnHomePage.Checked = product.ShowOnHomePage;

                this.cbAllowCustomerReviews.Checked = product.AllowCustomerReviews;
                this.cbAllowCustomerRatings.Checked = product.AllowCustomerRatings;
                this.cbPublished.Checked = product.Published;

                var productReviews = product.ProductReviews;
                if (productReviews.Count > 0) {
                    hlViewReviews.Visible = true;
                    hlViewReviews.Text = string.Format(GetLocaleResourceString("Admin.ProductInfo.AllowCustomerReviewsView"), productReviews.Count);
                    hlViewReviews.NavigateUrl = CommonHelper.GetStoreAdminLocation() + "ProductReviews.aspx?ProductID=" + product.ProductId.ToString();
                }
                else
                    hlViewReviews.Visible = false;

                this.txtProductTags.Text = GenerateListOfProductTagss(this.ProductService.GetProductTagsByProductId(product.ProductId));
                chkForceDisplayWoVat.Checked = product.ForceDisplayWOVat;
            }
        }

        private string GenerateListOfProductTagss(List<ProductTag> productTags) {
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < productTags.Count; i++) {
                ProductTag pt = productTags[i];
                result.Append(pt.Name.ToString());
                if (i != productTags.Count - 1) {
                    result.Append(", ");
                }
            }
            return result.ToString();
        }

        private string[] ParseProductTags(string productTags) {
            List<string> result = new List<string>();
            string[] values = productTags.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string val1 in values) {
                if (!String.IsNullOrEmpty(val1.Trim())) {
                    result.Add(val1);
                }
            }
            return result.ToArray();
        }

        public Product SaveInfo() {
            Product product = this.ProductService.GetProductById(this.ProductId);
            if (product != null) {
                product.Name = txtName.Text;
                product.ShortDescription = txtShortDescription.Text;
                product.FullDescription = txtFullDescription.Text;
                product.AdminComment = txtAdminComment.Text;
                product.TemplateId = int.Parse(ddlTemplate.SelectedItem.Value);
                product.ProductTypeId = int.Parse(ddlProductType.SelectedItem.Value);
                product.ShowOnHomePage = cbShowOnHomePage.Checked;
                product.AllowCustomerReviews = cbAllowCustomerReviews.Checked;
                product.AllowCustomerRatings = cbAllowCustomerRatings.Checked;
                product.Published = cbPublished.Checked;
                product.UpdatedOn = DateTime.UtcNow;
                product.ForceDisplayWOVat = chkForceDisplayWoVat.Checked;

                this.ProductService.UpdateProduct(product);

                SaveLocalizableContent(product);

                //product tags
                var existingProductTags = this.ProductService.GetProductTagsByProductId(product.ProductId);
                string[] newProductTags = ParseProductTags(txtProductTags.Text);
                var productTagsToDelete = new List<ProductTag>();
                foreach (var existingProductTag in existingProductTags) {
                    bool found = false;
                    foreach (string newProductTag in newProductTags) {
                        if (existingProductTag.Name.Equals(newProductTag, StringComparison.InvariantCultureIgnoreCase)) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        productTagsToDelete.Add(existingProductTag);
                    }
                }
                foreach (var productTag in productTagsToDelete) {
                    this.ProductService.RemoveProductTagMapping(product.ProductId, productTag.ProductTagId);
                }
                foreach (string productTagName in newProductTags) {
                    ProductTag productTag = null;
                    var productTag2 = this.ProductService.GetProductTagByName(productTagName);
                    if (productTag2 == null) {
                        //add new product tag
                        productTag = new ProductTag() {
                            Name = productTagName,
                            ProductCount = 0
                        };
                        this.ProductService.InsertProductTag(productTag);
                    }
                    else {
                        productTag = productTag2;
                    }
                    if (!this.ProductService.DoesProductTagMappingExist(product.ProductId, productTag.ProductTagId)) {
                        this.ProductService.AddProductTagMapping(product.ProductId, productTag.ProductTagId);
                    }
                }
            }

            return product;
        }

        protected void SaveLocalizableContent(Product product) {
            if (product == null)
                return;

            if (!this.HasLocalizableContent)
                return;

            foreach (RepeaterItem item in rptrLanguageDivs.Items) {
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) {
                    var txtLocalizedName = (TextBox)item.FindControl("txtLocalizedName");
                    var txtLocalizedShortDescription = (TextBox)item.FindControl("txtLocalizedShortDescription");
                    var txtLocalizedFullDescription = (TextBox)item.FindControl("txtLocalizedFullDescription");
                    var hfLanguageId = (HiddenField)item.FindControl("hfLanguageId");

                    int languageId = int.Parse(hfLanguageId.Value);
                    string name = txtLocalizedName.Text;
                    string shortDescription = txtLocalizedShortDescription.Text;
                    string fullDescription = txtLocalizedFullDescription.Text;

                    bool allFieldsAreEmpty = (string.IsNullOrEmpty(name) &&
                        string.IsNullOrEmpty(shortDescription) &&
                        string.IsNullOrEmpty(fullDescription));

                    var content = this.ProductService.GetProductLocalizedByProductIdAndLanguageId(product.ProductId, languageId);
                    if (content == null) {
                        if (!allFieldsAreEmpty && languageId > 0) {
                            //only insert if one of the fields are filled out (avoid too many empty records in db...)
                            content = new ProductLocalized() {
                                ProductId = product.ProductId,
                                LanguageId = languageId,
                                Name = name,
                                ShortDescription = shortDescription,
                                FullDescription = fullDescription
                            };
                            this.ProductService.InsertProductLocalized(content);
                        }
                    }
                    else {
                        if (languageId > 0) {
                            content.LanguageId = languageId;
                            content.Name = name;
                            content.ShortDescription = shortDescription;
                            content.FullDescription = fullDescription;
                            this.ProductService.UpdateProductLocalized(content);
                        }
                    }
                }
            }
        }

        protected void rptrLanguageDivs_ItemDataBound(object sender, RepeaterItemEventArgs e) {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
                var txtLocalizedName = (TextBox)e.Item.FindControl("txtLocalizedName");
                var txtLocalizedShortDescription = (TextBox)e.Item.FindControl("txtLocalizedShortDescription");
                var txtLocalizedFullDescription = (TextBox)e.Item.FindControl("txtLocalizedFullDescription");
                var hfLanguageId = (HiddenField)e.Item.FindControl("hfLanguageId");

                int languageId = int.Parse(hfLanguageId.Value);

                var content = this.ProductService.GetProductLocalizedByProductIdAndLanguageId(this.ProductId, languageId);
                if (content != null) {
                    txtLocalizedName.Text = content.Name;
                    txtLocalizedShortDescription.Text = content.ShortDescription;
                    txtLocalizedFullDescription.Text = content.FullDescription;
                }
            }
        }

        public int ProductId {
            get {
                return CommonHelper.QueryStringInt("ProductId");
            }
        }
    }
}